﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Nxg.Blog.Core.Documents;

namespace Nxg.Blog.Core.Commands.Accounts {
    public class LoginCommand {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public bool RememberMe { get; set; }

        public string ReturnUrl { get; set; }
    }

    public class LoginCommandResult : CommandResult {
        public LoginCommandResult () : base () { }

        public LoginCommandResult (string trrorMessage) : base (trrorMessage) { }

        public Author Author { get; set; }
    }

    public class LoginCommandInvoker : ICommandInvoker<LoginCommand, LoginCommandResult> {
        private readonly DataContext _db;
        private readonly IConfiguration _conf;

        public LoginCommandInvoker (DataContext db, IConfiguration conf) {
            _db = db;
            _conf = conf;
        }

        public LoginCommandResult Execute (LoginCommand loginCommand) {

            var email = _conf.GetValue<string> ("BlogSettings:Email");
            var displayName = _conf.GetValue<string> ("BlogSettings:DisplayName");
            var password = _conf.GetValue<string> ("BlogSettings:Password");
            var hashedPassword = Hasher.GetMd5Hash (loginCommand.Password);
            if (_db.Author.Count (x => true) == 0) {
                var newAuthor = new Author {
                Email = email,
                DisplayName = displayName,
                Roles = "admin",
                HashedPassword = Hasher.GetMd5Hash (password)
                };

                _db.Author.Add (newAuthor);
                _db.SaveChanges ();
            }
            var author = _db.Author.Where (x => x.Email == loginCommand.Email && x.HashedPassword == hashedPassword);
            if (author.Count () > 0) {
                var single = author.FirstOrDefault ();
                return new LoginCommandResult () { Author = single };
            }

            return new LoginCommandResult (trrorMessage: "login fail") { };
        }
    }
}